package de.uni.muenster.idw2.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class MyImage {

	private ImagePosition[] points;
	private Drawable drawable;
	private String imageID;

	// Create MyImage object from Drawable
	public MyImage(Context context, ImagePosition[] points, Drawable drawable) {
		this.points = points;
		this.drawable = drawable;
	}

	// Create MyImage object from URL
	public MyImage(Context context, ImagePosition[] points, String imageURL) {
		this.points = points;
		this.drawable = ImageOperations(context, imageURL);
	}

	/**
	 * @return the points
	 */
	public ImagePosition[] getPoints() {
		return points;
	}

	/**
	 * @param points
	 *            the points to set
	 */
	public void setPoints(ImagePosition[] points) {
		this.points = points;
	}

	/**
	 * @return the drawableID
	 */
	public Drawable getDrawable() {
		return drawable;
	}

	/**
	 * @param drawable
	 *            the drawableID to set
	 */
	public void setDrawableID(Drawable drawable) {
		this.drawable = drawable;
	}

	/**
	 * @return the imageID
	 */
	public String getImageID() {
		return imageID;
	}

	/**
	 * @param imageID
	 *            the imageID to set
	 */
	public void setImageID(String imageID) {
		this.imageID = imageID;
	}

	public boolean isNull() {
		return (drawable == null);
	}

	private Drawable ImageOperations(Context context, String url) {
		try {
			InputStream is = (InputStream) this.fetch(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			Log.e("ANALYSIS", "MalformedURLException");
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("ANALYSIS", "IOException");
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,
			IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	public void addPoint(ImagePosition ip) {
		if (points == null) {
			points = new ImagePosition[1];
			points[0] = ip;
		}
		else {
			ImagePosition[] temp = new ImagePosition[points.length + 1];
			for (int i = 0; i < points.length; i++) {
				temp[i] = points[i];				
			}
			temp[points.length] = ip;
			points = temp;
		}
	}
	
	public String toString() {
		return "\n" + imageID + ":\n" + Arrays.toString(points);
	}

}
